<template>
  <a-modal
    v-model:open="visible"
    title="创建图片"
    width="800px"
    :footer="null"
    :destroy-on-close="true"
    @cancel="handleCancel"
  >
    <div id="addPictureModal">
      <!-- 选择保存位置 -->
      <div style="margin-bottom: 24px">
        <h3 style="margin-bottom: 12px">选择保存位置</h3>
        <a-radio-group v-model:value="saveLocation" style="width: 100%">
          <a-space direction="vertical" style="width: 100%">
            <a-radio value="public" style="width: 100%">
              <a-card size="small" style="width: 100%; margin-left: 24px" hoverable>
                <template #title>
                  <a-space>
                    <GlobalOutlined />
                    公共图库
                  </a-space>
                </template>
                <p style="margin: 0; color: #666">
                  上传到公共图库，所有用户都可以浏览和使用
                </p>
              </a-card>
            </a-radio>
            <a-radio value="private" style="width: 100%">
              <a-card size="small" style="width: 100%; margin-left: 24px" hoverable>
                <template #title>
                  <a-space>
                    <LockOutlined />
                    私有图库
                  </a-space>
                </template>
                <p style="margin: 0; color: #666">
                  上传到您的私有空间，只有您可以访问和管理
                </p>
              </a-card>
            </a-radio>
          </a-space>
        </a-radio-group>
      </div>
      
      <a-typography-paragraph v-if="saveLocation" type="secondary">
        保存至：{{ saveLocation === 'public' ? '公共图库' : '私有图库' }}
      </a-typography-paragraph>
      
      <!-- 选择上传方式 -->
      <a-tabs v-model:activeKey="uploadType">
        <a-tab-pane key="file" tab="文件上传">
          <!-- 图片上传组件 -->
          <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
        <a-tab-pane key="url" tab="URL 上传" force-render>
          <!-- URL 图片上传组件 -->
          <UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
        </a-tab-pane>
      </a-tabs>
      
      <!-- 图片编辑 -->
      <div v-if="picture" class="edit-bar">
        <a-space size="middle">
          <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
          <a-button type="primary" :icon="h(FullscreenOutlined)" @click="doImagePainting">
            AI 扩图
          </a-button>
        </a-space>
        <ImageCropper
          ref="imageCropperRef"
          :imageUrl="picture?.url"
          :picture="picture"
          :spaceId="spaceId"
          :space="space"
          :onSuccess="onCropSuccess"
        />
        <ImageOutPainting
          ref="imageOutPaintingRef"
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onImageOutPaintingSuccess"
        />
      </div>
      
      <!-- 图片信息表单 -->
      <a-form
        v-if="picture"
        name="pictureForm"
        layout="vertical"
        :model="pictureForm"
        @finish="handleSubmit"
      >
        <a-form-item name="name" label="名称">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" allow-clear />
        </a-form-item>
        <a-form-item name="introduction" label="简介">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="category" label="分类">
          <a-auto-complete
            v-model:value="pictureForm.category"
            placeholder="请输入分类"
            :options="categoryOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="tags" label="标签">
          <a-select
            v-model:value="pictureForm.tags"
            mode="tags"
            placeholder="请输入标签"
            :options="tagOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <a-space style="width: 100%; justify-content: flex-end">
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" html-type="submit" :loading="submitLoading">创建</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import {
  editPictureUsingPost,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import PictureUpload from '@/components/PictureUpload.vue'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import { EditOutlined, FullscreenOutlined, GlobalOutlined, LockOutlined } from '@ant-design/icons-vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'

interface Props {
  open?: boolean
  onSuccess?: () => void
  onCancel?: () => void
}

const props = defineProps<Props>()

const visible = ref(false)
const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const uploadType = ref<'file' | 'url'>('file')
const submitLoading = ref(false)

// 保存位置选择
const saveLocation = ref<'public' | 'private'>('public')

// 空间 id - 根据选择的保存位置计算
const spaceId = computed<string | undefined>(() => {
  // 如果选择的是私有图库，返回 undefined（让后端自动处理）
  // 如果选择的是公共图库，返回 undefined（后端会保存到公共图库）
  return undefined
})

// 监听props.open变化
watchEffect(() => {
  visible.value = props.open || false
})

/**
 * 图片上传成功
 * @param newPicture
 */
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  console.log(values)
  const pictureId = picture.value?.id
  if (!pictureId) {
    return
  }
  
  submitLoading.value = true
  try {
    const res = await editPictureUsingPost({
      id: pictureId,
      spaceId: spaceId.value,
      ...values,
    })
    
    // 操作成功
    if (res.data.code === 0 && res.data.data) {
      message.success('创建成功')
      handleCancel()
      props.onSuccess?.()
    } else {
      message.error('创建失败，' + res.data.message)
    }
  } finally {
    submitLoading.value = false
  }
}

/**
 * 取消操作
 */
const handleCancel = () => {
  visible.value = false
  // 重置状态
  picture.value = undefined
  pictureForm.name = undefined
  pictureForm.introduction = undefined
  pictureForm.category = undefined
  pictureForm.tags = undefined
  saveLocation.value = 'public'
  uploadType.value = 'file'
  
  props.onCancel?.()
}

const categoryOptions = ref<{ value: string; label: string }[]>([])
const tagOptions = ref<{ value: string; label: string }[]>([])

/**
 * 获取标签和分类选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('获取标签分类列表失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})

// ----- 图片编辑器引用 ------
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = async () => {
  imageCropperRef.value?.openModal()
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// ----- AI 扩图引用 -----
const imageOutPaintingRef = ref()

// 打开 AI 扩图弹窗
const doImagePainting = async () => {
  imageOutPaintingRef.value?.openModal()
}

// AI 扩图保存事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// 获取空间信息
const space = ref<API.SpaceVO>()

// 暴露打开弹窗的方法
const openModal = () => {
  visible.value = true
}

defineExpose({
  openModal
})
</script>

<style scoped>
#addPictureModal {
  max-width: 100%;
}

#addPictureModal .edit-bar {
  text-align: center;
  margin: 16px 0;
}

/* 黑色模式适配 */
[data-theme="dark"] #addPictureModal {
  color: #e5e7eb;
}

[data-theme="dark"] #addPictureModal .ant-card {
  background: rgba(55, 65, 81, 0.8) !important;
  border-color: rgba(75, 85, 99, 0.5) !important;
}

[data-theme="dark"] #addPictureModal .ant-card:hover {
  border-color: rgba(14, 165, 233, 0.6) !important;
}

[data-theme="dark"] #addPictureModal .ant-card .ant-card-head-title {
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureModal .ant-card .ant-card-body p {
  color: #9ca3af !important;
}

[data-theme="dark"] #addPictureModal .ant-typography {
  color: #9ca3af !important;
}

[data-theme="dark"] #addPictureModal .ant-form-item-label > label {
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureModal .ant-input,
[data-theme="dark"] #addPictureModal .ant-select-selector {
  background: rgba(55, 65, 81, 0.8) !important;
  border-color: rgba(75, 85, 99, 0.5) !important;
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureModal .ant-input:hover,
[data-theme="dark"] #addPictureModal .ant-select:hover .ant-select-selector {
  border-color: rgba(14, 165, 233, 0.6) !important;
}

[data-theme="dark"] #addPictureModal .ant-input:focus,
[data-theme="dark"] #addPictureModal .ant-input-focused,
[data-theme="dark"] #addPictureModal .ant-select-focused .ant-select-selector {
  border-color: #0ea5e9 !important;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.2) !important;
}

[data-theme="dark"] #addPictureModal .ant-input::placeholder,
[data-theme="dark"] #addPictureModal .ant-select-selection-placeholder {
  color: #9ca3af !important;
}
</style>
